package com.example.test.support;


import android.text.TextUtils;

import com.blankj.utilcode.util.SPUtils;
import com.example.test.support.interceptor.CommonRequestInterceptor;
import com.example.test.support.interceptor.CommonResponseInterceptor;
import com.example.test.support.interceptor.UploadFileRequestInterceptor;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 网络接口请求基本抽象类
 *
 * @author xgh
 */
public abstract class BaseNetworkApi implements IEnvironment {

    /*** 成功*/
    public static final String RESPONSE_CODE_SUCCESS = "0";
    /*** 没有查询到数据*/
    public static final String RESPONSE_CODE_NO_DATA = "100";
    /*** 获取Token验证账号失败	接口token*/
    public static final String RESPONSE_CODE_APP_TOKEN_ERROR = "101";
    /*** 接口入参异常*/
    public static final String RESPONSE_CODE_PARAMS_ERROR = "102";
    /*** Token失效或不存在	接口token*/
    public static final String RESPONSE_CODE_APP_TOKEN_INVALID = "103";
    /*** 登陆Token失效	登陆token*/
    public static final String RESPONSE_CODE_USER_TOKEN_INVALID = "104";
    /*** 账号被挤下线*/
    public static final String RESPONSE_CODE_KICK = "105";
    /**
     * 系统维护中
     */
    public static final String RESPONSE_CODE_SYSTEM_MAINTENANCE = "302";
    /*** 其他异常 */
    public static final String RESPONSE_CODE_ERROR = "-1";

    public static INetworkRequiredInfo iNetworkRequiredInfo;
    // retrofit实例对象Map
    private static HashMap<String, Retrofit> retrofitHashMap = new HashMap<>();
    protected String mBaseUrl;
    private OkHttpClient mOkHttpClient;

    /*** app token */
    private volatile static String auth_token;

    public static String getAuth_token() {
        if (TextUtils.isEmpty(auth_token)) {
            auth_token = SPUtils.getInstance().getString("auth_token");
        }
        return auth_token;
    }

    public static void setAuth_token(String authToken) {
        SPUtils.getInstance().put("auth_token", authToken);
        auth_token = authToken;
    }

    public BaseNetworkApi() {
        mBaseUrl = getFormal();
    }

    /**
     * 初始化
     */
    public static void init(INetworkRequiredInfo networkRequiredInfo) {
        iNetworkRequiredInfo = networkRequiredInfo;
    }

    /**
     * 获取Retrofit的实例
     *
     * @param service 具体的某个网络接口请求类，用来生成retrofitHashMap的key
     */
    protected Retrofit getRetrofit(Class service) {
        if (retrofitHashMap.get(mBaseUrl + service.getName()) != null) {
            return retrofitHashMap.get(mBaseUrl + service.getName());
        }


        Retrofit.Builder retrofitBuilder = new Retrofit.Builder();
        retrofitBuilder.baseUrl(mBaseUrl);
        retrofitBuilder.client(getOkHttpClient());
        retrofitBuilder.addConverterFactory(GsonConverterFactory.create(GsonUtils.getLocalGson()));
        Retrofit retrofit = retrofitBuilder.build();
        retrofitHashMap.put(mBaseUrl + service.getName(), retrofit);
        return retrofit;
    }

    /**
     * 获取OkHttp请求代理
     */
    protected OkHttpClient getOkHttpClient() {
        if (mOkHttpClient == null) {
            OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
            okHttpClientBuilder.connectTimeout(20, TimeUnit.SECONDS);
            okHttpClientBuilder.readTimeout(60, TimeUnit.SECONDS);
            okHttpClientBuilder.writeTimeout(40, TimeUnit.SECONDS);


            int cacheSize = 100 * 1024 * 1024; // 100MB
            okHttpClientBuilder.cache(new Cache(iNetworkRequiredInfo.getApplicationContext().getCacheDir(), cacheSize));
            //添加公共请求拦截器
            okHttpClientBuilder.addInterceptor(new CommonRequestInterceptor(iNetworkRequiredInfo));

            //判断自定义请求拦截器是否为空
            if (getRequestInterceptor() != null) {
                //自定义拦截器不为空，加入自定义拦截器
                okHttpClientBuilder.addInterceptor(getRequestInterceptor());
            }

            //添加公共响应拦截器
            okHttpClientBuilder.addInterceptor(new CommonResponseInterceptor());

            //判断自定义响应拦截器是否为空
            if (getResponseInterceptor() != null) {
                //自定义拦截器不为空，加入自定义拦截器
                okHttpClientBuilder.addInterceptor(getResponseInterceptor());
            }

            // 上传文件图片拦截器
            okHttpClientBuilder.addInterceptor(new UploadFileRequestInterceptor());

            //Debug调试模式时，加入拦截器，打印日志
            if (iNetworkRequiredInfo != null && (iNetworkRequiredInfo.isDebug())) {
                HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
                httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                okHttpClientBuilder.addInterceptor(httpLoggingInterceptor);
            }

            mOkHttpClient = okHttpClientBuilder.build();
        }


        return mOkHttpClient;
    }


    /**
     * 获取自定义请求拦截器
     */
    protected abstract Interceptor getRequestInterceptor();

    /**
     * 获取自定义响应拦截器
     */
    protected abstract Interceptor getResponseInterceptor();


}
